import inspect
import sys,os,time
p=os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))
p=os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(p))))
p=p+os.sep+'_base_tool'+os.sep+'python'
sys.path.append(p)
from base_class1_0 import base_class # type: ignore
import tornado.ioloop
import tornado.web
import json as JSON
import httpx
 
class a_1_0_2_3_0(base_class):  
    def init(self,*a,**b):
        self.requests={
            'get':self.http_get,
            'post':self.http_post,
            'delete':self.http_delete,
            'put':self.http_put
        }
     # 定义一个函数，用于发起GET请求  
    def http_get(self,url, headers=None,**k):  
        with httpx.Client() as client:  
            response = client.get(url, headers=headers)  
            return response
    
    # 定义一个函数，用于发起POST请求  
    def http_post(self,url, headers=None, json=None,**k):  
        with httpx.Client() as client:  
            response = client.post(url, headers=headers, json=json)  
            return response
    
    # 定义一个函数，用于发起PUT请求  
    def http_put(self,url, headers=None, json=None,**k):  
        with httpx.Client() as client:  
            response = client.put(url, headers=headers, json=json)  
            return response
    
    # 定义一个函数，用于发起DELETE请求  
    def http_delete(self,url, headers=None,**k):  
        with httpx.Client() as client:  
            response = client.delete(url, headers=headers)  
            return response
    def run(self, method, url,headers=None, params=None, json=None,**kwargs):   
        print('json:',json)
        if headers=='':headers=None
        elif isinstance(headers,str):headers=JSON.loads(headers)
        if json=='':json=None
        elif isinstance(json,str):json=JSON.loads(json.strip())
        full_url = url +('?'+params if params else '')
        response=self.requests[method](url=full_url,headers=headers,json=json)
        res={}
        try:
            res['json']=response.json()
        except:pass
        res['text']=response.text
        return res
    #目前先不用  以后有时间了再优化成协程函数
    async def run_async(self, method, url,headers=None, params=None, json=None,**kwargs):   
        """  
        发起HTTP请求的基础方法  
        :param method: 请求方法（'GET', 'POST', 'PUT', 'DELETE'）  
        :param url: 请求的URL（如果提供了base_url，则这是相对路径）  
        :param params: URL参数 
        :param json: 请求体，JSON格式，字典将被自动转换为JSON字符串  
        :return: 响应的text和json（如果响应内容可以转换为JSON）  
        """  
        if isinstance(params,dict) is True:params=JSON.dumps(params)
        full_url = url +('?'+params if params else '')
        async with httpx.AsyncClient() as client:  
            response = await client.request(  
                method=method,  
                url=full_url,  
                json=json,
                headers=headers
            )  
            response.raise_for_status()  # 如果响应状态码不是2xx，则抛出HTTPError异常  
            res={}
            try:
                res['json']=response.json()
            except:pass
            res['text']=response.text
            return res
  